import React, { useState, useEffect } from 'react';
import { Button, Modal, Form, Input, InputNumber, Spin, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { getMaxSort, dictAdd } from '@/services/system/dict';

// 定义传参
interface DictAddParams {
  refresh: () => void;
}

/**
 * 新建字典
 *
 * @author zhangby
 * @date 22/9/20 11:15 am
 */
const DictAdd: React.FC<DictAddParams> = (props) => {
  const { refresh } = props;
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);

  const [form] = Form.useForm();

  // 初始化
  const onPreInit = async () => {
    setVisible(true);
    form.resetFields();
    // 查询最大排序
    try {
      setLoading(true);
      const maxSort = await getMaxSort('');
      form.setFieldsValue({
        sort: maxSort.result?.maxSort,
      });
      setLoading(false);
    } catch (e) {
      // 设置默认
      form.setFieldsValue({
        sort: 10,
      });
      setLoading(false);
    }
  };

  // 保存
  const onSubmit = () => {
    form.validateFields().then(async (values) => {
      try {
        setLoading(true);
        // 新建字典
        const data = await dictAdd(values);
        if (data.code === '000') {
          message.success('新建字典成功');
          setLoading(false);
          setVisible(false);
          refresh();
        }
      } catch (e) {
        setLoading(false);
      }
    });
  };

  return (
    <>
      <Button type="primary" onClick={onPreInit}>
        <PlusOutlined />
        新建
      </Button>
      <Modal
        title="新建字典"
        visible={visible}
        onOk={onSubmit}
        onCancel={() => setVisible(false)}
        width={600}
      >
        <Spin spinning={loading}>
          <Form {...layout} form={form} initialValues={{}}>
            <Form.Item
              name="label"
              label="字典名称"
              rules={[{ required: true, message: '字典名称不能为空' }]}
            >
              <Input placeholder="字典名称" />
            </Form.Item>
            <Form.Item
              name="type"
              label="字典类型"
              rules={[{ required: true, message: '字典类型不能为空' }]}
            >
              <Input placeholder="字典类型" />
            </Form.Item>
            <Form.Item name="sort" label="排序" initialValue={10}>
              <InputNumber min={0} step={1} precision={0} />
            </Form.Item>
            <Form.Item name="description" label="描述">
              <Input.TextArea placeholder="字典描述" autoSize={{ minRows: 3, maxRows: 5 }} />
            </Form.Item>
          </Form>
        </Spin>
      </Modal>
    </>
  );
};

const layout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 12 },
  },
};

export default DictAdd;
